package com.bridgeintelligent.tag.webserver.dim.mgmt.service.datamonitoring;

import com.bridgeintelligent.tag.mapper.DatamonitoringMapper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.vo.DimAssessVO;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.datamonitoring.model.Datamonitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @description 标签数据监控
 * @author: xiayan 2020-10-13
 **/
@Service
@AllArgsConstructor
@Slf4j
public class DatamonitoringServiceImpl implements  DatamonitoringService {

    private static final String PATTERN1 = "yyyy-MM";

    private static final String PATTERN2 = "yyyy-MM-dd";

    private DatamonitoringMapper datamonitoringMapper;
    @Override
    public DimAssessVO getInfo(String dimId) {
        DimAssessVO assessVO = new DimAssessVO();
        DimAssessVO.DimBaseInfo dimBaseInfo = datamonitoringMapper.findDimBaseInfo(dimId);
        if(dimBaseInfo !=null){
            boolean result= dimBaseInfo.getShowType() != null && dimBaseInfo.getShowType().matches("[0-9]+");
            if(dimBaseInfo.getDataSource()==null){
                String source=datamonitoringMapper.findDateSource(dimId);
                dimBaseInfo.setDataSource(source);
            }
            if (result) {
                String str =datamonitoringMapper.findShowRule(dimBaseInfo.getShowType());
                dimBaseInfo.setShowType(str);
            }
        }
        getConvertDate(dimBaseInfo);
        assessVO.setBaseInfo(dimBaseInfo);
        return assessVO;
    }
    @Override
    public DimAssessVO getStatistics(String dimId) {
        DimAssessVO assessVO = new DimAssessVO();
        DimAssessVO.DimBaseInfo dimBaseInfo = datamonitoringMapper.findDimBaseInfo(dimId);
        getConvertDate(dimBaseInfo);
       List<DimAssessVO.DimQualityInfo> dimQualityInfo;
        if(StringUtils.equals("02",dimBaseInfo.getDimLargeType())){
            dimQualityInfo = datamonitoringMapper.findDimFreeQualityInfo(dimId);
        }else{
            dimQualityInfo = datamonitoringMapper.findDimQualityInfo(dimId);
        }
        if(!CollectionUtils.isEmpty(dimQualityInfo)){
            assessVO.setQualityInfo(dimQualityInfo.get(0));
        }
        List<DimAssessVO.DimUseInfo> dimUseInfo = datamonitoringMapper.findDimUseInfo(dimId);
        DimAssessVO.DimUseInfo  dimUse = new DimAssessVO.DimUseInfo();
        if(dimUseInfo.size()>0){
            dimUse.setTotalCount(dimUseInfo.get(0).getCombinaCount()+ dimUseInfo.get(0).getCustomerCount());
            dimUse.setSearchCount(dimUseInfo.get(0).getSearchCount());
            dimUse.setDowloadCount(dimUseInfo.get(0).getDowloadCount());
        }
        List<DimAssessVO.DimUseInfo> dimUseInfop=new ArrayList<>();
        dimUseInfop.add(dimUse);
        assessVO.setUseInfo(dimUseInfop);
        //  User user = SecurityHelper.currentUser();
        // assessVO.setAssessInfo(datamonitoringMapper.selectByOwner(user.getUserId(),dimId));
        return assessVO;
    }

    @Override
    public List<Datamonitoring> getStatcount(String dimId) {
        List<Datamonitoring> datamonitoringlist;
        datamonitoringlist=datamonitoringMapper.getStatcount(dimId);
        return datamonitoringlist;
    }

    @Override
    public List<Datamonitoring> getComment(String dimId,String star) {
        List<Datamonitoring> datamonitoringlist;
        List<String> codelist = new ArrayList<>();
        datamonitoringlist=datamonitoringMapper.getComment(dimId,star);
        for(Datamonitoring datam : datamonitoringlist){
            codelist.add(datam.getCode());
        }
        datamonitoringlist.clear();
        Map<String, Object> listMap = getListMap(codelist);
        for(String key : listMap.keySet()){
            Datamonitoring datamonitoring = new Datamonitoring();
                datamonitoring.setBfb(division((Integer)listMap.get(key),(Integer)listMap.get("count")));
                datamonitoring.setCode(key);
                datamonitoring.setFcount(listMap.get(key).toString());
                if(!key.equals("count")){
                    datamonitoringlist.add(datamonitoring);
                }
        }

        return datamonitoringlist;
    }

    @Override
    public List<Datamonitoring> getHistory(String dimId) {
        List<Datamonitoring> datamonitoringlist;
        List<Datamonitoring> datamonitoringlistxz;
        List<Datamonitoring> datamonitoringlistcount = new ArrayList<>();
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        Date now = ca.getTime();
        ca.add(Calendar.YEAR, -1); //年份减1
        Date lastMonth = ca.getTime();//减去一年后的时间
        SimpleDateFormat sfxz = new SimpleDateFormat(PATTERN1);
        String startTimexz =sfxz.format(lastMonth);
        String endTimexz = sfxz.format(now);
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -1); //天数减1
        SimpleDateFormat nsfxz = new SimpleDateFormat(PATTERN2);
        String nowTime = nsfxz.format(ca.getTime());
        log.info("startTimexz:"+startTimexz+"------endTimexz:"+endTimexz+"----nowTime:"+nowTime);
        datamonitoringlist=datamonitoringMapper.getHistory(dimId,startTimexz,endTimexz,nowTime);
        datamonitoringlistxz=datamonitoringMapper.getHistoryxz(dimId,startTimexz,endTimexz,nowTime);
        datamonitoringlistcount.addAll(datamonitoringlistxz);
        datamonitoringlistcount.addAll(datamonitoringlist);
        return datamonitoringlistcount;
    }


    @Override
    public List<Datamonitoring> getDetailed(String dimId,String star) {
        List<Datamonitoring> datamonitoringlist;
        datamonitoringlist=datamonitoringMapper.getDetailed(dimId,star);
        return datamonitoringlist;
    }

    public static Map<String, Object> getListMap(List<String> strArr) {
        List<String> str = new ArrayList<String>();
        int start=1;
        int end =8;
        for (int i = 0; i < strArr.size(); i++) {
            List<String> strings = Arrays.asList(strArr.get(i).split(","));
            str.addAll(strings);
        }
        for(int i = start; i<= end; i++){
            if( ! str.contains(String.valueOf(i)) ){
                str.add(String.valueOf(i)+"K");
            }
        }
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < str.size();i++) {
            boolean flag = map.containsKey(str.get(i));
            int result1 = str.get(i).indexOf("K");
            if (flag) {
                int value = (int)map.get(str.get(i));
                map.put(str.get(i), value + 1);
            }else if(result1 != -1){
                map.put(str.get(i).replace("K",""), 0);
            }else {
                map.put(str.get(i), 1);
            }
        }
        map.put("count",str.size());
        return map;
    }
    private void getConvertDate(DimAssessVO.DimBaseInfo dimBaseInfo) {
        if(dimBaseInfo==null){
            return;
        }
        if(StringUtils.length(dimBaseInfo.getUptTime())>10){
            dimBaseInfo.setUptTime(StringUtils.substring(dimBaseInfo.getUptTime(),0,10));
        }
        if(StringUtils.equals("02",dimBaseInfo.getDimLargeType())||StringUtils.equals("04",dimBaseInfo.getDimLargeType())){
            dimBaseInfo.setEffectiveTime(dimBaseInfo.getApproveDate());
        }
        if(StringUtils.length(dimBaseInfo.getEffectiveTime())>10){
            dimBaseInfo.setEffectiveTime(StringUtils.substring(dimBaseInfo.getEffectiveTime(),0,10));
        }
    }

    /**
     * rate 保留2位小数的
     */
    public static String  division(int num1,int num2){
        String rate="0.00%";
        //定义格式化起始位数
        String format="0.00";
        if(num2 != 0 && num1 != 0){
            DecimalFormat dec = new DecimalFormat(format);
            rate =  dec.format((double) num1 / num2*100)+"%";
            while(true){
                if(rate.equals(format+"%")){
                    format=format+"0";
                    DecimalFormat dec1 = new DecimalFormat(format);
                    rate =  dec1.format((double) num1 / num2*100)+"%";
                }else {
                    break;
                }
            }
        }else if(num1 != 0 && num2 == 0){
            rate = "100%";
        }
        return rate;
    }

}
